$(function() {
    // 判断用户是否登录 - 判断cookie中是否存有username
    var username = getCookie('username')
    var login = document.querySelector(".login");
    if (username) {
        var str = `
        <li><a href="">欢太商城APP</a></li>
        <li><a href="javascript:;"><i class="iconfont icon-yonghu"></i><span>${username}</span>
            </a></li>
            <li><a href="javascript:;" class="logout">退出</a></li>
        <li><a href="../html/cart.html"><i class="iconfont icon-gouwuchekong"></i><span>购物车</span><span class="qwe">(0)</span></a></li>
        `
        login.innerHTML = str;
        // 退出功能
        var logout = document.querySelector(".logout");
        logout.onclick = function() {
            layer.confirm('你确定要退出吗？', {
                    btn: ['确定', '取消'] //按钮
                },
                function() {
                    // 删除cookie
                    delCookie('username');
                    login.innerHTML = `
                    <li><a href="">欢太商城APP</a></li>
                    <li><a href="./login.html"><i class="iconfont icon-yonghu"></i><span>登录</span>
                        </a></li>
                    <li><a href="./register.html">注册</a></li>
                    <li><a href="../html/cart.html" class="num"><i class="iconfont icon-gouwuchekong"></i><span>购物车</span><span>0</span></a></li>
                    `
                    var msgindex = layer.msg("退出成功", {
                        icon: 1
                    })
                    setTimeout(function() {
                        layer.close(msgindex)
                        location.href = '../html/list.html';
                    }, 2000)
                },
                function() {
                    layer.msg("已取消", {
                        icon: 1,
                        time: 500
                    })
                    return false;
                }
            );
        }
    } else {
        // 用户没有登录就让用户去登陆
        var msgindex = layer.msg("请先登录", {
            icon: 2,
        })
        setTimeout(function() {
            layer.close(msgindex)
            location.href = 'login.html';
        }, 2000)
    }

    // 请求购物车数据
    var data = localStorage.getItem('data');
    if (!data || JSON.parse(data).length == 0) {
        var str = `
        <div class="empty">
        <img src="https://dsfs.oppo.com/oppo/shop-pc-v2/main/img/dd9b2d3.png" alt="">
        <h5>购物车还没有商品</h5>
        <p><a class="btn btn-danger btn-lg" href="list.html" role="button">去列表页逛逛</a></p>
    </div>
        `
        $('.cart .content').html(str)
    } else {
        var arr = JSON.parse(data);
        if (!arr.length) {
            var str = `
            <div class="empty">
            <img src="https://dsfs.oppo.com/oppo/shop-pc-v2/main/img/dd9b2d3.png" alt="">
            <h5>购物车还没有商品</h5>
            <p><a class="btn btn-danger btn-lg" href="list.html" role="button">去列表页逛逛</a></p>
        </div>
            `
            $('.cart .content').html(str)
            return false;
        }
        // 从本地存储中获取到所有当前用户的数据
        var brr = arr.map(v => {
            if (v.username === username) {
                return v.id
            }
        });
        var trr = JSON.parse(data);
        var trr = trr.map(v => {
            if (v.username === username) {
                return v.num
            }
        });
        var alll = 0;
        for (var i = 0; i < trr.length; i++) {
            alll += parseInt(trr[i])
        }
        // alert($('.login .qwe').text())
        //获取购物车的数量
        $('.login .qwe').text("(" + alll + ")")
        $('.slide .num').text(alll)
            // 将所有数据的商品id拼接在一起
        var ids = brr.join(',')
            //   console.log(ids);
        var loadindex = layer.load(0, { shade: true });
        $.ajax({
            url: '../server/cart.php',
            data: { ids },
            dataType: "json",
            success(res) {
                //   console.log(res);
                // var data = res.data
                var { data } = res;
                var str = '';
                //   console.log(data);
                for (var i = 0; i < data.length; i++) {
                    var number = arr.find(v => v.username === username && v.id == data[i].id).num
                    str += `
                        <tr valign="bottom">
                            <td><input type="checkbox" name="selectOne"></td>
                            <td><img src="${data[i].imgpath.split('========')[0]}" width="50" height="50"></td>
                            <td>${data[i].h3}</td>
                            <td class="price">￥<span>${data[i].price}</span></td>
                            <td class="number" data-stock="${data[i].stock}" data-id="${data[i].id}">
                                <button class="btn btn-default reduce">-</button>
                                <input type="text" name="number" value="${number}">
                                <button class="btn btn-default add">+</button>
                            </td>
                          <td class="subtotal">￥<span>${data[i].price * number}</span></td>
                            <td><button class="btn btn-danger remove">移除</button></td>
                        </tr>
                    `
                }
                $('.cart table tbody').html(str)
                layer.close(loadindex)
                firstReduce()
                    // 全选单选事件
                select();
                // 数量加减
                addAndReduce()
                    // 移除
                remove()
                    // 计算总数和总价
                total()
            }
        })
    }
    // 计算总数和总价
    function total() {
        var totalNum = 0;
        var totalPrice = 0
        $('[name="selectOne"]:checked').each(function(i, v) {
            totalNum += $(v).parent().siblings('.number').find('input[name="number"]').val() - 0
            totalPrice += $(v).parent().siblings('.subtotal').find('span').text() - 0
        })
        $('.totalNum').text(totalNum)
        $('.totalPrice').text(totalPrice)
    }
    // 全选单选
    function select() {
        $('[name="selectAll"]').click(function() {
            $('[name="selectOne"]').prop('checked', $(this).prop('checked'))
            $('[name="selectAll"]').prop('checked', $(this).prop('checked'))
            total()
        })
        $('[name="selectOne"]').click(function() {
            //   将jq获取的集合转为一个元素数组集合
            var selectArr = Array.prototype.slice.call($('[name="selectOne"]'))
                //   只有数组中的元素都是checked 返回才是true
            var selectStatus = selectArr.every(v => v.checked)
                // 所以的单选都选上的时候后，全选也勾选上
            $('[name="selectAll"]').prop('checked', selectStatus)
            total()
        })
    }

    function firstReduce() {
        // var inps = document.querySelectorAll('input[name = number]')
        // inps.forEach(function(item, index) {
        //     console.log(item);
        //     console.log(item.previousElementSibling);
        //     if (item.value == 1) {
        //         item.previousElementSibling.setAttribute('disabled', true)
        //     }
        // })
        $('table .number .reduce').mouseover(function() {
            // alert(545)
            if ($(this).next().val() - 0 <= 1) {
                $(this).prop('disabled', true)

            }
        })
        $('table .number .add').mouseover(function() {
            // alert(545)
            if ($(this).prev().val() - 0 >= $('.number').attr('data-stock')) {
                $(this).prop('disabled', true)

            }
        })
    }

    // 数量加减
    function addAndReduce() {
        $('table .number .add').click(function() {
            var num = $(this).prev().val() - 0;
            $('table .number .reduce').prop('disabled', false)
            num++;
            if (num >= $(this).parent().attr('data-stock')) {
                num = $(this).parent().attr('data-stock')
                $(this).prop('disabled', true)
            }
            alll++;
            $('.login .qwe').text("(" + alll + ")")
            $('.slide .num').text(alll)
            $(this).prev().val(num)
                // 修改本地存储
            var data = JSON.parse(localStorage.getItem('data'))
            var id = $(this).parent().attr('data-id');
            var obj = data.find(v => v.username === username && v.id === id)
            obj.num = num;
            localStorage.setItem('data', JSON.stringify(data))
                // 计算小计
            var price = $(this).parent().siblings(".price").find('span').text() - 0
            var subtotal = price * num;
            $(this).parent().siblings('.subtotal').find('span').text(subtotal)
            total()
        })
        $('table .number .reduce').click(function() {
            var num = $(this).next().val() - 0;
            $('table .number .add').prop('disabled', false)
            num--;
            if (num <= 1) {
                num = 1
                $(this).prop('disabled', true)
            }
            alll--;
            $('.login .qwe').text("(" + alll + ")")
            $('.slide .num').text(alll)
            $(this).next().val(num)
                // 修改本地存储
            var data = JSON.parse(localStorage.getItem('data'))
            var id = $(this).parent().attr('data-id');
            var obj = data.find(v => v.username === username && v.id === id)
            obj.num = num;
            // $('.login .num span:last').text(num)
            // alert($('.login .num span:last').text(num))
            localStorage.setItem('data', JSON.stringify(data))
                // 计算小计
            var price = $(this).parent().siblings(".price").find('span').text() - 0
            var subtotal = price * num;
            $(this).parent().siblings('.subtotal').find('span').text(subtotal)
            total()
        })
    }
    // 移除
    function remove() {
        $('.remove').click(function() {
                var that = $(this)
                layer.confirm('你确定要删除吗？', {
                        btn: ['确定', '取消'] //按钮
                    },
                    function() {
                        //   拿到本地localStorage中的数据
                        var data = JSON.parse(localStorage.getItem('data'))
                            //   获取到景点id
                        var id = that.parent().siblings('.number').attr('data-id');
                        var val = that.parent().siblings('.number').find('input').val() - 0
                        alll -= val
                            // $('.login .qwe').text("(" + parseInt(alll - val) + ")")
                        $('.login .qwe').text("(" + alll + ")")
                            // $('.slide .num').text(parseInt(alll - val))
                        $('.slide .num').text(alll)
                            //   获取到要删除的景点在data中的索引
                        var index = data.findIndex(v => v.username === username && v.id === id)
                            //   删除data中的对应的景点信息
                        data.splice(index, 1)
                            //   移除页面元素
                        that.parent().parent().remove()
                        total()
                            //   将移除之后的数据写入localStorage
                        localStorage.setItem('data', JSON.stringify(data))
                        layer.msg("删除成功", {
                                icon: 1,
                                time: 500
                            })
                            // location.reload();
                        data = JSON.parse(localStorage.getItem('data'))
                        if (!data.length) {
                            var str = `
                        <div class="empty">
                        <img src="https://dsfs.oppo.com/oppo/shop-pc-v2/main/img/dd9b2d3.png" alt="">
                        <h5>购物车还没有商品</h5>
                        <p><a class="btn btn-danger btn-lg" href="list.html" role="button">去列表页逛逛</a></p>
                    </div>
                        `
                            $('.cart .content').html(str)
                        }
                    },
                    function() {
                        layer.msg("已取消", {
                            icon: 1,
                            time: 500
                        })
                        return false;
                    }
                );

            })
            // location.reload();
    }

})